package io.renren.modules.mqtt.service;

import com.alibaba.fastjson.JSON;
import io.renren.modules.mqtt.EventServiceFactory;
import io.renren.modules.mqtt.entity.MqttEvent;
import io.renren.modules.mqtt.entity.MqttLog;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * //Add the class description
 *
 * @author lhb
 * @date 2023/8/4
 */

@Service
@Slf4j
public class MqttService {

    public static String InfoTopic = "zhny-event";
    @Autowired
    private IMqttLogService mqttLogService;

    @Async
    public void handleMqttMessage(String topic, MqttMessage message) {
        String payLoad = new String(message.getPayload());
        log.info("收到message: \n  topic：" + topic + "\n  Qos：" + message.getQos() + "\n  payload：" + payLoad);
        MqttLog mqttLog = new MqttLog();
        mqttLog.setTopic(topic);
        mqttLog.setMessage(new String(message.getPayload()));
        mqttLog.setQos(message.getQos());
        mqttLog.setCreateTime(new Date());
        mqttLogService.save(mqttLog);

        MqttEvent mqttEvent = JSON.parseObject(payLoad, MqttEvent.class);
        mqttEvent.setTopic(topic);
        // 处理收到的mqtt消息
        if (EventServiceFactory.handleEventMessage(mqttEvent)) {
            log.debug("处理event: {}, 成功", payLoad);
        } else {
            log.debug("处理event: {}, 失败", payLoad);
        }
    }

    public void subscribe(MqttAsyncClient client) throws MqttException {
        log.info("开始订阅主题:{}", InfoTopic);
        client.subscribe(InfoTopic, 1);
//        try {
//            for (String t : topic.split(",")) {
//                client.subscribe(t, 1);
//            }
//        } catch (MqttException e) {
//            e.printStackTrace();
//        }
    }
}
